﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using SOM.Common;
using SOM.ConcreteBL;
using SOM.Model;

public partial class Administracao_ReclamacoesAdm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Usuario usuario = Common.RetornarUsuarioSessao(this);

            if (usuario == null)
            {
                FormsAuthentication.RedirectToLoginPage();
                return;
            }

            if (usuario.usr_id_grupo != (int)GrupoDoUsuario.Administrador)
            {
                Response.Redirect("~/Erro/AcessoNegado.aspx");
                return;
            }

            CarregarGrid();
        }

        if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"].ToString() != string.Empty)
        {
            ExcluirReclamacao(int.Parse(Request["__EVENTARGUMENT"]));
        }
    }

    protected void grvReclamacoesUsuario_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HyperLink hlkExcluirReclamacao = (HyperLink)e.Row.FindControl("hlkExcluirReclamacao");
            hlkExcluirReclamacao.NavigateUrl = "javascript:Excluir('" + e.Row.Cells[0].Text + "')";

            HyperLink hplVerMapa = (HyperLink)e.Row.FindControl("hplVerMapa");
            hplVerMapa.NavigateUrl =
                "javascript:AbrirPopup(\"../Reclamacao/PopupReclamacaoLocalizacao.aspx?op=1&recId=" +
                SOM.Security.SOMSecurity.Codificar(e.Row.Cells[0].Text) + "\")";

            HyperLink hplReclamacaoDetalhes = (HyperLink)e.Row.FindControl("hypVisualizarReclamacao");
            string idReclamacao = SOM.Security.SOMSecurity.Codificar(e.Row.Cells[0].Text);
            hplReclamacaoDetalhes.NavigateUrl = "~/Reclamacao/ReclamacaoDetalhes.aspx?op=1&recId=" + idReclamacao;

            ReclamacaoBL reclamacaoBL = new ReclamacaoBL();
            Reclamacao reclamacao = reclamacaoBL.Load(int.Parse(idReclamacao));
            DropDownList ddlStatusReclamacao = (DropDownList)e.Row.FindControl("ddlStatusReclamacao");
            ddlStatusReclamacao.SelectedValue = reclamacao.rec_id_status.ToString();
        }
    }
    protected void grvReclamacoes_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        ReclamacaoBL reclamacaoBL = new ReclamacaoBL();
        grvReclamacoes.DataSource = reclamacaoBL.ReturnAll().OrderBy(rec => rec.rec_dt_data);
        grvReclamacoes.SelectedIndex = e.NewSelectedIndex;
        grvReclamacoes.DataBind();
    }
    protected void btnSalvar_Click(object sender, EventArgs e)
    {
        ReclamacaoBL reclamacaoBL = new ReclamacaoBL();

        foreach (GridViewRow row in grvReclamacoes.Rows)
        {
            DropDownList ddlStatusReclamacao = (DropDownList)row.FindControl("ddlStatusReclamacao");
            Reclamacao reclamacao = reclamacaoBL.Load(int.Parse(row.Cells[0].Text));

            reclamacao.rec_id_status = int.Parse(ddlStatusReclamacao.SelectedItem.Value);

            reclamacaoBL.Update(reclamacao);
        }
    }

    protected void btnCancelar_Click(object sender, EventArgs e)
    {
        Response.Redirect(FormsAuthentication.DefaultUrl);
    }

    private void ExcluirReclamacao(int idReclamacao)
    {
        try
        {
            ReclamacaoBL reclamacaoBL = new ReclamacaoBL();

            reclamacaoBL.Delete(idReclamacao);

            CarregarGrid();
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("Sua reclamação não pode ser excluída." + ex.Message);
        }
    }
    protected void btnPesquisar_Click(object sender, EventArgs e)
    {
        CarregarGrid();
    }

    //Atualiza o gridview de reclamacoes
    private void CarregarGrid()
    {
        Usuario usuario = Common.RetornarUsuarioSessao(this);
        ReclamacaoBL reclamacaoBL = new ReclamacaoBL();

        List<Reclamacao> reclamacoesList = new List<Reclamacao>();

        DateTime dataInicial = string.IsNullOrEmpty(txtDataInicial.Text) ? Convert.ToDateTime("01-01-1753") : Convert.ToDateTime(txtDataInicial.Text);
        DateTime dataFinal = string.IsNullOrEmpty(txtDataFinal.Text) ? DateTime.MaxValue : Convert.ToDateTime(txtDataFinal.Text);

        if (usuario == null)
        {
            FormsAuthentication.RedirectToLoginPage();
            return;
        }

        if (dataFinal < DateTime.MaxValue)
        {
            dataFinal = dataFinal.AddDays(1);
        }

        if(dataInicial > DateTime.MinValue)
        {
            dataInicial = dataInicial.AddDays(-1);
        }

        if (rblMetodoPesquisa.SelectedItem.Value.Equals("palavraChave"))
        {
          
            reclamacoesList = reclamacaoBL.FindByDataFiltro(dataInicial, dataFinal,
                                          OpcaoPesquisa.PalavraChave, txtPesquisa.Text);
        }

        if (rblMetodoPesquisa.SelectedItem.Value.Equals("descricao"))
        {
            reclamacoesList = reclamacaoBL.FindByDataFiltro(dataInicial, dataFinal,
                                         OpcaoPesquisa.Descricao, txtPesquisa.Text);
        }

            grvReclamacoes.DataSource = reclamacoesList;
            grvReclamacoes.DataBind();
    }
}
